﻿--[[File:ActorLoginHandler.lua]]
--To do something about Login and Logout

--#include "ActorDataFunc.lua" once
--#include "data\config\TasksConfig.inc" once --活动开始配置
--#include "data\config\activityconfig\Dart\DartConfig.lua"  once  --基本设置
	--#include "data\functions\Tasks\LuoYangBattle\BattleCommon.lua" once

--#include "data\config\activity\seckill.lua" once	--秒活动
--#include "data\config\quest\MiscQuest.lua" once
--#include "data\functions\player.lua" once -- 角色处理
--#include "data\config\guild\GuildSiegeConfig.lua" once  --行会
--#include "data\functions\Guild\GuildSbkWar.lua" once --攻城战
--#include "data\functions\Activity\Operation\operation.lua" once   --运营活动
--#include "data\functions\Guild\GuildContendWar.lua" once          --行会争夺

-------------------------------------------------------------------------------------------
--死亡后重新登陆的判断
EventCallDispatcher._LoginLoginResurrection = function (sysarg)
	if Actor.getIntProperty(sysarg,PROP_CREATURE_HP) == 0 then
		------------------------------------------------------------
		--掉落操作
		PkDropFunc(sysarg)
		
		--清除击杀者信息
		ClearKillerData(sysarg)
		----------------------------------------------------------
		
		Actor.relive(sysarg)
		if Actor.getIntProperty(sysarg,PROP_CREATURE_HP) == 0 then
	    local maxhp = Actor.getIntProperty(sysarg,PROP_CREATURE_MAXHP) 
			Actor.changeHp(sysarg, math.floor(maxhp*0.3))
			local actorMp = Actor.getIntProperty(sysarg,PROP_CREATURE_MP)
			local maxmp = Actor.getIntProperty(sysarg,PROP_CREATURE_MAXMP)
			--print("actorMp:"..actorMp)
			Actor.changeMp(sysarg,-(actorMp - math.floor(maxmp*0.3)))
		end
		Actor.addBuff(sysarg,65,1,1,1,15,Lang.ScriptTips.b00009)
	end
end


-------------------------------------------------------------------------------------------
--[[
处理玩家登陆
]]
EventCallDispatcher.defaultHandlerPlayerLogin = function (sysarg,arg)
	local isFirstLogin = arg[1]
	local isCrossDayLogin = arg[2]
	local verifyCheckValue = arg[3]
	
	EventCallDispatcher._LoginLoginResurrection(sysarg)

	--跨服限制
	if OnCsActorLoginLmt() == false then 
		--第一次登陆
		if (isFirstLogin == 1) then
			OnPlayerFirstLogin(sysarg)
		end

		--跨月登陆
		local logoutTime = Actor.getLastLogoutTime(sysarg)
		local curTime = System.getCurrMiniTime()
		if not System.isSameMonth(curTime,logoutTime) then	
			OnPlayerCrossMonth( sysarg )
		end

		--跨天登陆
		if isCrossDayLogin ~= 0 then
			OnPlayerLoginAnotherDay( sysarg ) 			--该方法仅玩家跨天后登陆
			OnPlayerCrossDay(sysarg)					--该方法玩家在线跨天或者跨天登陆
		end

		--跨6点登陆
		local logoutTime = Actor.getLastLogoutTime(sysarg)
		local curHour = System.getTime(0, 0, 0)
		local nYear, nMonth, nDay = System.getDate(0, 0, 0)
		local todaySixTime = System.encodeNumTime(nYear, nMonth, nDay, 6, 0, 0)
		if logoutTime + 86400 < todaySixTime or (curHour > 6 and logoutTime < todaySixTime) then
			OnActorEventNewDaySixClock(sysarg)
		end

		--加载玩家数据
		loadActorData(sysarg)

		if isFirstLogin == 1 then
			verifyCheckLoginGame(sysarg, verifyCheckValue)
		end
	else
		OnBossSoulLogin(sysarg)
		SendOpenServerDays(sysarg)
	end
end

function SetAnswerTitle( sysarg )
	local myName = Actor.getName(sysarg)
	local sysVar = System.getStaticVar()
	local lastRanking = Ranking.getRanking( Lang.Rank.LastWeekAnswer )
	if lastRanking then
		local item = Ranking.getItemFromIndex(lastRanking, 0)
		if item then
			local topName = Ranking.getSub(item, 0)
			if topName == myName then
				--Actor.addTopTitle(sysarg, AnswerConfig.TitleId)
			end
		end
	end
	--处理文采值是否过期
	local sVar = Actor.getStaticVar(sysarg)
	if sVar.AnswerPoints then
		if sysVar.AnswerResetDt and sVar.LastGetAnswerPtDt and sysVar.AnswerResetDt > sVar.LastGetAnswerPtDt then
			sVar.AnswerPoints = nil
			sVar.LastGetAnswerPtDt = nil
		else
			-- PROP_ACTOR_KNOWLEDGE_POINT 改为了 PROP_ACTOR_CURRENT_HEAD_TITLE, 如果以后前端还需要 sVar.AnswerPoints 这个就话就单独下发吧
			--Actor.setUIntProperty(sysarg, PROP_ACTOR_KNOWLEDGE_POINT, sVar.AnswerPoints)
		end
	end
end

function inviteBrotherTeam(sysarg,arg)
	if arg == nil then
		return
	end
	local ptr = System.getEntityPtrByActorID(arg)
	if ptr ~= nil then
		Actor.inviteJoinTeam(sysarg,ptr)
	end
end

--发送个人押镖剩余次数
function SendApplyDartLeftTimes(sysarg)
	local var = Actor.getStaticVar(sysarg)
	if not var.days then var.days = {} end
	if var.days.darttms == nil then
		var.days.darttms = 0
	end

	--vip类型
	local bVip = Actor.isVip(sysarg)
					
	local maxTimes = 0
	if(bVip == true) then
		maxTimes = EscortDartConfig.VipOpenTimes
	else
		maxTimes = EscortDartConfig.OpenTimes
	end
	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, 8) --分配一个数据包
	if(pack~=nil) then
		DataPack.writeInt(pack,maxTimes - var.days.darttms)

		DataPack.flush(pack) --向客户端发送
	end
end

--秒活动副本参加数据
function ResetSecKill(sysarg)
	local lastLogoutTime = Actor.getLastLogoutTime(sysarg)
	local loginTime = System.getCurrMiniTime()
	
	if System.isSameDay(loginTime, lastLogoutTime) == true then
		return
	end
	
	local config = SecKill
	if not config then return end
	local circle = Actor.getIntProperty(sysarg, PROP_ACTOR_CIRCLE)
	if circle > 0 then return end
	local level = Actor.getIntProperty(sysarg, PROP_CREATURE_LEVEL)
	local maxId = 1
	for k, v in ipairs(config) do
		if v.id > maxId then
			maxId = v.id
		end
		if v.level == 0 or level < v.level then
			--Actor.setWorkDayMask(sysarg, 0, v.id, false)
			Actor.setWorkDayMask(sysarg, 1, v.id, true)
			Actor.setWorkDayMask(sysarg, 2, v.id, true)
			Actor.setWorkDayMask(sysarg, 3, v.id, true)
		end
	end
	
	for i=(maxId+1), 64 do
		Actor.setWorkDayMask(sysarg, 0, i, true)
	end
end

function OnRemoveLastSbkLeader(sysarg)
		
	local newSbkLeaderId = Guild.getSbkCityOwner()
	--local oldSbkLeaderId = Guild.getLastSbkOwnerId()
	local actorId = Actor.getIntProperty(sysarg,PROP_ENTITY_ID)
	if newSbkLeaderId ~= actorId then  --
		local nJob = Actor.getIntProperty(sysarg,PROP_ACTOR_VOCATION)
		local nBuffType = 12
		if nJob == 2 then 
			nBuffType = 16 
		elseif nJob == 3 then 
			nBuffType = 20
		end
		Actor.delBuff(sysarg,nBuffType,206)
	end
	
	local nItem = Item.getItemByType(sysarg,1,true)
	if nItem then
		if Item.getItemId(nItem) == 834 and Item.getItemProperty(sysarg, nItem, Item.ipItemLuck, 0) > 7	then
			Item.setItemProperty(sysarg, nItem, Item.ipItemLuck, 7)
		end
	end
end


function OnAddPet(sysarg)
	--宝宝上线加载
	--[[
	local var = Actor.getStaticVar(sysarg)
	if var.petInfo then
		local ai = {260, 261, 262}
		local petId = var.petInfo[1]
		local nCurHp = var.petInfo[2]
		local nIndex = Pet.addPet(sysarg,petId,1,ai[petId-255],0)
		local petPtr = Pet.getPetById(sysarg,nIndex)
		var.petId = nIndex
		Actor.setIntProperty(petPtr,PROP_CREATURE_HP,nCurHp)
		Actor.setSocialMask(sysarg,smisHasPet,true)
		if var.addTempAck and var.addTempAck[1] then
			local nCurTime = System.getCurrMiniTime()
			if nCurTime - var.addTempAck[1]	< 0 then
				local combatAttr = {}
				for i = 13,22 do	--最小物理攻击属性开始到最大魔法防御TypeId
					table.insert(combatAttr,Actor.getIntProperty(petPtr,i))
				end
				
				local attrType = {9,11,13,15,17,19,21,23,25,27}
				for key,value in ipairs(attrType) do
					Pet.setIntAddAttr(petPtr,value,combatAttr[key]*(var.addTempAck[2]-1))
				end
				Actor.collectOperate(petPtr,0)
				
				local npack = DataPack.allocPacket(sysarg, 34, 1)
				if not npack then return end 
				DataPack.writeInt(npack,var.addTempAck[1]-nCurTime)
				DataPack.writeByte(npack,var.addTempAck[2])	
				DataPack.flush(npack)
			else
				var.addTempAck = nil
			end
		end
	else
		Actor.setSocialMask(sysarg,smisHasPet,false)
	end
	]]
end

function QuestFuBen(sysarg)

	if not AcceptQuestCfg then return end

	for _,QuestData in pairs(AcceptQuestCfg) do
		
		local nFatherQuest = Actor.isFinishQuest(sysarg,QuestData.FatherQuestID)
		local nCurQuest = Actor.isFinishQuest(sysarg,QuestData.CurQuestID)
		if nFatherQuest and not nCurQuest then
			local Hfuben = Fuben.createFuBen(QuestData.FubenID)
			Actor.enterFuBen(sysarg,Hfuben,QuestData.SceneID,unpack(QuestData.Pos))
			return
		elseif nCurQuest and not Actor.canFinishQuest(QuestData.SonQuestID) and not Actor.isFinishQuest(sysarg,QuestData.SonQuestID) then
			local Hfuben = Fuben.createFuBen(QuestData.FubenID)
			Actor.enterFuBen(sysarg,Hfuben,QuestData.SceneID,unpack(QuestData.Pos))
			return
		end
	end
end

-- datetime：活动时间（字符串），格式：2016-1-1 2016-1-15
function AllActivityButtonState(sysarg,Type,State, datetime)
	
	local netPack = DataPack.allocPacket(sysarg, LogicCmd.miscSys.sub.sysId, LogicCmd.miscSys.sub.sActivityIconStatus)
	DataPack.writeByte(netPack,Type)  	--类型 ，对应客户端图标图片的ID
	DataPack.writeByte(netPack,State)	--0：隐藏， 1：显示
	if State ~= 0 then -- 开启
		DataPack.writeUInt(netPack,0) -- 开启时间
		DataPack.writeUInt(netPack,0) -- 结束时间
	end
	
	if datetime ~= nil then
		DataPack.writeString(netPack, datetime)
	end
	
	DataPack.flush(netPack)	
end

function ClearActorCombinedFlag(sysarg)
	
	local var = Actor.getStaticVar(sysarg)

	if var.CombineLoginGift then var.CombineLoginGift = nil end
	if var.CombineCumulativeFlag then var.CombineCumulativeFlag = nil end
	if var.SuperBagGift then var.SuperBagGift = nil end
	if var.CombineCumulative then var.CombineCumulative = nil end
	if var.CombineLotteryScore then var.CombineLotteryScore = nil end
	if var.CombineLotteryId then var.CombineLotteryId = nil end
	if var.CombineLoginDay then var.CombineLoginDay = nil end
end

function ClearCombinedFlag(sysarg)
	
	ClearActorCombinedFlag(sysarg)
	local sVar = System.getStaticVar()
	if sVar.CombineSbkLeader then sVar.CombineSbkLeader = nil end
	if sVar.CombineSbkMasses then sVar.CombineSbkMasses = nil end	
end

function LearnSkill(sysarg)
	
	local vLv = Actor.getVipGrade(sysarg)
	local nJob = Actor.getIntProperty(sysarg,PROP_ACTOR_VOCATION)
	local nLevel = Actor.getIntProperty(sysarg,PROP_CREATURE_LEVEL)
	
	local skillId = 
	{
		--战士
		{},	
		--法师
		{},	
		 --道士
		{{skill_Id = 71,needLevel = 80,needCircle = 0}},  --学习技能：技能ID，达到所需的等级、转数
	}
	local nJobSkill = assert(skillId[nJob],"skill table is nil")
	for _,skill in ipairs(nJobSkill) do
		if Actor.getSkillLevel(sysarg,skill.skill_Id) <= 0 and Actor.checkActorLevel(sysarg,skill.needLevel,skill.needCircle) then
			if vLv > 0 then
				Actor.startLearnSkill(sysarg,skill.skill_Id,3)
			else
				Actor.startLearnSkill(sysarg,skill.skill_Id,1)
			end
		end
	end		
end

--如果领取微信礼包就不下发
function SendHideWeixin(sysarg)
	local var = Actor.getStaticVar(sysarg)
	if var.HasGetWeixinGiftFlag then
		local pack = DataPack.allocPacket(sysarg, LogicCmd.miscSys.sysId, LogicCmd.miscSys.sub.sSendWeChatGift)
		DataPack.flush(pack)
	end
end

--在线跨天
function OnActorEventNewDayAcrrive(sysarg,arg)
	ProcRetrieveResNewDay( sysarg ) 				--处理资源回收（要在充值操作次数之前调用）
	OnPlayerCrossDay(sysarg)						--var.days = {}在这里执行
	
	local nYear,nMonth,nDay = System.getDate()
	if nDay == 1 then 		--进入新的一月第1天
		OnPlayerCrossMonth( sysarg )
	end

	SendOpenServerDays(sysarg)	--开服天数
	OnGuildNewDay( sysarg ) 	--在线跨天的行会处理
end

--[[玩家跨天登陆（非在线跨天）
在 OnPlayerCrossDay(sysarg) 之前执行
]]
function OnPlayerLoginAnotherDay( sysarg )
	OnRetrieveResLogin( sysarg )
end

-- 新的一天6点
function OnActorEventNewDaySixClock(sysarg, arg)
	OnSwingNewDaySixClock(sysarg)
end

function OnPlayerFirstLogin(sysarg)
	Actor.addBuffById(sysarg,  GlobalConfig.nNewPlayerProtectBuffId ) --新手buff
	OnDefaultFirstLogin(sysarg)
end

EventCallDispatcher.registerEventCall(BaseTypes.ActorEventId.aeUserLogin, EventCallDispatcher.defaultHandlerPlayerLogin)
EventCallDispatcher.registerEventCall(BaseTypes.ActorEventId.aeNewDayArrive, OnActorEventNewDayAcrrive)
EventCallDispatcher.registerEventCall(BaseTypes.ActorEventId.aeNewDaySixClock, OnActorEventNewDaySixClock)
